﻿using IM.Easy.ScheduledServices.IServices;
using Quartz;
using Quartz.Listener;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.ScheduledServices.Dtos
{
    // <summary>
    /// 监听并记录触发器执行情况的监听器。
    /// </summary>
    public class ScheduledLogger : TriggerListenerSupport
    {
        private readonly IScheduledJobService scheduledJobService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="scheduledJobService"></param>
        public ScheduledLogger(IScheduledJobService scheduledJobService)
        {
            this.scheduledJobService = scheduledJobService;
        }

        /// <summary>
        /// 获取监听器的名称。
        /// </summary>
        public override string Name => "ScheduledLogger";

        /// <summary>
        /// 当触发器完成时调用。
        /// </summary>
        /// <param name="trigger">触发器实例。</param>
        /// <param name="context">作业执行上下文。</param>
        /// <param name="triggerInstructionCode">触发器指令代码。</param>
        public override async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
        {
            try
            {
                var job = scheduledJobService.GetById(context.JobDetail.Key.Name);
                job.NextFireTime = trigger.GetNextFireTimeUtc()?.LocalDateTime;
                job.LastFireTime = trigger.GetPreviousFireTimeUtc()?.LocalDateTime;
                job.FireCount += 1;
                scheduledJobService.Update(job);
            }
            catch
            {
                Console.WriteLine("未能正常记录执行日志");
            }
        }
    }
}
